<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <ControlWrap
    :customStyle="{
      background: '#f9fafb',
    }"
  >
    <div>
      <div class="px-4 sm:px-6 lg:px-8 py-8">
        <!-- 顶部操作区 -->
        <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
          <div class="flex justify-between items-center">
            <el-button
              type="primary"
              class="!rounded-button"
              @click="handleAdd"
            >
              <el-icon class="mr-1"><Plus /></el-icon>新建角色
            </el-button>
            <div class="flex items-center gap-4">
              <el-input
                v-model.trim="searchForm.keyword"
                placeholder="请输入用户名称"
                style="width: 200px"
                :prefix-icon="Search"
                clearable
              />
              <el-select
                v-model="searchForm.status"
                placeholder="用户账号状态"
                style="width: 100px"
              >
                <el-option label="全部" :value="0" />
                <el-option label="正常" :value="1" />
                <el-option label="停用" :value="2" />
              </el-select>
              <el-button
                type="primary"
                class="!rounded-button"
                @click="handleSearch"
              >
                <el-icon class="mr-1"><Search /></el-icon>搜索
              </el-button>
              <el-button class="!rounded-button" @click="resetSearch"
                >重置</el-button
              >
            </div>
          </div>
        </div>
        <!-- 用户列表 -->
        <div
          class="bg-white rounded-lg shadow overflow-hidden border border-gray-100"
        >
          <el-table
            :data="filteredUsers"
            style="width: 100%"
            v-loading="loading"
            :row-class-name="tableRowClassName"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="用户信息" min-width="280">
              <template #default="{ row }">
                <div class="flex items-center gap-3">
                  <el-avatar :size="40" :src="row.avatar" />
                  <div>
                    <div class="font-medium text-gray-900">{{ row.name }}</div>
                    <div class="text-sm text-gray-500">{{ row.email }}</div>
                    <div
                      class="text-xs text-blue-600 bg-blue-50 rounded-full px-2 py-0.5 inline-block mt-1"
                    >
                      {{ row.roleName ? row.roleName : "非法角色" }}
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="性别" min-width="150">
              <template #default="{ row }">
                <div class="flex items-center gap-2">
                  <span>{{ row.sex == 1 ? "男" : "女" }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              min-width="150"
            />
            <el-table-column prop="birthDate" label="生日" min-width="150" />
            <el-table-column
              prop="loginExpiresIn"
              label="登录有效期"
              min-width="150"
            />
            <el-table-column prop="lastLogin" label="最近登录" width="200">
              <template #default="{ row }">
                <div class="flex items-center gap-2 text-gray-600">
                  <el-icon><Clock /></el-icon>
                  <span>{{ row.lastLogin }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="200">
              <template #default="{ row }">
                <div class="flex items-center gap-2 text-gray-600">
                  <el-icon><Clock /></el-icon>
                  <span>{{ row.updateTime }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="活跃度" width="200">
              <template #default="{ row }">
                <div class="flex items-center gap-2">
                  {{ row.activity }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="180">
              <template #default="{ row }">
                <div class="flex items-center gap-2 flex-wrap">
                  <el-button
                    type="primary"
                    link
                    @click="handleEdit(row)"
                    class="flex items-center"
                  >
                    <el-icon class="mr-1"><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button
                    type="primary"
                    link
                    v-if="row.loginExpiresIn"
                    @click="handleEditLoginInfo(row)"
                    class="flex items-center"
                  >
                    <el-icon class="mr-1"><Edit /></el-icon>
                    修改登录有效期
                  </el-button>
                  <el-button
                    type="danger"
                    link
                    @click="handleDelete(row)"
                    class="flex items-center"
                  >
                    <el-icon class="mr-1"><Delete /></el-icon>
                    删除
                  </el-button>
                  <el-button
                    type="danger"
                    link
                    v-if="row.loginExpiresIn"
                    @click="handleDeleteLoginInfo(row)"
                    class="flex items-center"
                  >
                    <el-icon class="mr-1"><Delete /></el-icon>
                    清除刷新令牌记录
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <div class="flex justify-between items-center px-4 py-3">
            <div class="text-sm text-gray-700">共 {{ total }} 条记录</div>
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 30, 50]"
              layout="sizes, prev, pager, next"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
      <!-- 用户表单对话框 -->
      <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="form.role" class="w-full">
              <el-option
                v-for="(item, index) in permissionOption"
                :key="index"
                :label="item.role_name"
                :value="item.role_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="账号状态">
            <el-switch
              :active-value="1"
              :inactive-value="2"
              v-model="form.status"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="flex justify-end gap-2">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </ControlWrap>
</template>
<script lang="ts" setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Edit, Delete, Clock } from "@element-plus/icons-vue";
import {
  getUserPageList,
  addUser,
  deleteUser,
  editUser,
  getUserInfo,
} from "@/api/user";
import { getAllRoleList } from "@/api/role";
import { delLoginManage, putLoginManage } from "@/api/loginManger";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
import { useDictStore } from "@/store/dict";
import { storeToRefs } from "pinia";
import Dict from "@/util/dictMap";
const dictStore = useDictStore();
const { getAllDict, getDictListByCode, getDictName, getDictValue } = dictStore;

dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const tableRowClassName = ({ rowIndex }: { rowIndex: number }) => {
  return rowIndex % 2 === 0 ? "bg-gray-50" : "";
};
const getActivityColor = (activity: number) => {
  if (activity >= 90) return "#67C23A";
  if (activity >= 70) return "#409EFF";
  if (activity >= 50) return "#E6A23C";
  return "#F56C6C";
};
const loading = ref(false);
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formRef = ref();
const form: any = ref({
  id: "",
  name: "",
  role: "",
  status: 1,
});
const searchForm = ref({
  keyword: "",
  status: 0,
});
const permissionOption: any = ref([]);
const rules = {
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  role: [{ required: true, message: "请选择角色", trigger: "change" }],
};
const users = ref<any[]>([]);
const filteredUsers = computed(() => {
  return users.value.filter(
    (user) =>
      user.name.includes(searchQuery.value) ||
      user.role.includes(searchQuery.value)
  );
});
const handleSearch = async () => {
  currentPage.value = 1;
  await getPageList();
};
const resetSearch = async () => {
  currentPage.value = 1;
  searchForm.value.keyword = "";
  searchForm.value.status = 0;
  await getPageList();
};
const handleSizeChange = async (val: number) => {
  pageSize.value = val;
  await getPageList();
};
const handleCurrentChange = async (val: number) => {
  currentPage.value = val;
  await getPageList();
};
const handleAdd = () => {
  dialogTitle.value = "新增用户";
  form.value = {
    id: "",
    name: "",
    role: "",
    status: 1,
  };
  dialogVisible.value = true;
};
const handleEdit = (row: any) => {
  dialogTitle.value = "编辑用户";
  form.value.id = row.userId;
  form.value.name = row.name;
  form.value.role = row.roleId.toString();
  form.value.status = row.status;
  dialogVisible.value = true;
  console.log(form.value);
};
const handleEditLoginInfo = (row: any) => {};
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确认删除该用户吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await deleteUser({ userId: row.userId });
    ElMessage.success("删除成功");
    await getPageList();
  });
};
const handleDeleteLoginInfo = (row: any) => {
  ElMessageBox.confirm(
    "确认删除该账号刷新令牌有效期记录？(访问令牌过期后自动触发登录)",
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
    await delLoginManage({ userId: row.userId });
    ElMessage.success("已删除刷新令牌有效期记录");
    await getPageList();
  });
};
const handleStatusChange = (row: any) => {
  ElMessage.success(`${row.name} 权限状态已${row.status ? "启用" : "禁用"}`);
};
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.id) {
        await editUser({
          userName: form.value.name,
          roleId: form.value.role,
          userId: form.value.id,
          status: form.value.status,
          errorMsg: true,
          successMsg: true,
        });
      } else {
        await addUser({
          userName: form.value.name,
          roleId: form.value.role,
          status: form.value.status,
          errorMsg: true,
          successMsg: true,
        });
      }
      await getPageList();
      dialogVisible.value = false;
      ElMessage.success("操作成功");
    }
  });
};
const handleExport = () => {
  ElMessage.success("数据导出成功");
};
const getPageList = async () => {
  loading.value = true;
  try {
    const res = await getUserPageList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      userName: searchForm.value.keyword,
      status: searchForm.value.status,
    });
    total.value = res.total;
    users.value = res.list.map((item: any) => {
      return {
        id: item.id,
        userId: item.user_id,
        name: item.user_name,
        roleName: item.roleName,
        roleId: item.role_id,
        email: item.email,
        status: item.status,
        avatar: item.user_header_img
          ? item.user_header_img
          : "https://ai-public.mastergo.com/ai/img_res/144ef7b2362c8736e599bb8109dc1e0f.jpg",
        lastLogin: dayjs(item.updateTime).fromNow(),
        activity: Number(item.liveness),
        birthDate: item.birth_date
          ? dayjs(item.birth_date).format("YYYY-MM-DD")
          : "保密",
        sex: item.sex,
        createTime: dayjs(item.createTime).format("YYYY-MM-DD HH:mm:ss"),
        updateTime: dayjs(item.updateTime).format("YYYY-MM-DD HH:mm:ss"),
        loginExpiresIn: item.loginExpiresIn
          ? dayjs(item.loginExpiresIn).format("YYYY-MM-DD HH:mm:ss")
          : null,
      };
    });
  } catch (error) {
    console.error("获取用户列表失败:", error);
  } finally {
    loading.value = false;
  }
};
onMounted(async () => {
  getAllRoleList({})
    .then((res: any) => {
      permissionOption.value = res;
    })
    .catch((err: any) => {
      console.error(err);
    });
  await getPageList();
});
</script>
<style scoped>
.el-input :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #e5e7eb inset;
}
.el-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}
.el-table {
  --el-table-border-color: #e5e7eb;
  --el-table-header-bg-color: #f8fafc;
  /* --el-table-tr-bg-color: transparent; */
}
.el-table :deep(thead th) {
  font-weight: 600;
  color: #1f2937;
}
.el-table :deep(tbody td) {
  padding: 16px 0;
}
.el-pagination {
  --el-pagination-button-bg-color: transparent;
}
.el-button--primary {
  --el-button-bg-color: #1890ff;
  --el-button-border-color: #1890ff;
  --el-button-hover-bg-color: #40a9ff;
  --el-button-hover-border-color: #40a9ff;
}
.el-dialog {
  --el-dialog-padding-primary: 20px;
}
.el-tag {
  height: 24px;
  line-height: 24px;
}
</style>
